package com.destroyer.core.util;

import com.destroyer.common.util.DateUtils;
import org.apache.commons.codec.Charsets;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 回复工具包
 */
public class ResponseUtil {

    public static void setResponse(HttpServletResponse response, String fileName, String type, boolean addTimestamp) throws UnsupportedEncodingException {
        String mmType = type;
        if ("xlsx".equals(type)) {
            mmType = "vnd.ms-excel";
        }
        response.setContentType("application/" + mmType);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        String encode = URLEncoder.encode(fileName + (addTimestamp ? DateUtils.getCurrentDateStrYYYYMMDDHHMMSS3() : ""), StandardCharsets.UTF_8.name());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + encode + "." + type + "\"");
    }

    /**
     * pdf 回复设置
     * @param response
     * @param fileName
     * @throws UnsupportedEncodingException
     */
    public static void setPdfResponse(HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
        setResponse(response, fileName, "pdf", true);
    }
    /**
     * Excel 回复设置
     * @param response
     * @param fileName
     * @throws UnsupportedEncodingException
     */
   public static void setExcelResponse(HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
        setResponse(response, fileName, "xlsx", true);
    }
    /**
     * zip 回复设置
     * @param response
     * @param fileName
     * @throws UnsupportedEncodingException
     */
    public static void setZipResponse(HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
        setResponse(response, fileName, "zip", true);
    }
}
